package calvin.study.rabbitmq.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

public class RabbitMqProducer extends RabbitMqBase {
	
	private static final Logger log = LoggerFactory.getLogger(RabbitMqProducer.class);
	
	/**
	 * 构造函数
	 * @param exchangeName 交换器名称
	 */
	public RabbitMqProducer(String exchangeName) {
		rabbitmqConfig = new RabbitMqConfig(null, "", exchangeName);
		init();
	}

	@Override
	protected RabbitMqModel initConnection(Connection conn) {
		String exchangeName = rabbitmqConfig.getExchangeName();
		try {
			Channel channel = conn.createChannel();
			//durable 是否持久化 为true时,服务器宕机重启,该交换机依然存在.
			channel.exchangeDeclare(exchangeName, "direct", true); // 使用direct模式
			RabbitMqModel mqModel = new RabbitMqModel(conn, channel); // 对于生产者，第三个参数consumer为空
			return mqModel;
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 发布消息
	 * @param msg
	 * @param key
	 */
	public void putMsg(byte[] msg, String key) {
		
		RabbitMqModel mqModel = getMQ();
		if (null == mqModel) {
			log.error(String.format("Can not get one connection to any mq, message is thrown, message is %s, key is %s", msg, key));
			return;
		}
		
		try {
			Channel channel = mqModel.getChannel();
			String exchangeName = rabbitmqConfig.getExchangeName();
			//expiration 消息过期时间 TTL 消息未被消费,过期后会成为死信
			//1.发送方指定
			//2.新建一个队列时指定
			channel.basicPublish(exchangeName, key, null, msg);
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		
	}
}
